package gis.utils;

import android.os.Handler;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;

/**
 * Created by Administrator on 2015/11/21.
 */

public class UploadUtil {

    File uploadFile;
    String fileName;
    int type;
    Handler handler;

    public UploadUtil(File file,int type, Handler handler) {
        // TODO Auto-generated constructor stub
        this.uploadFile = file;
        this.fileName = uploadFile.getName();
        this.type = type;
        this.handler = handler;
    }

    public boolean uploadFile() throws Exception
    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(Constants.URL_UPFILE);
        MultipartEntityBuilder builder =  MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //设置请求的编码格式
        //mpEntity.setCharset(Charset.forName("utf-8"));//这一句不能要

        builder.addTextBody("type", Integer.toString(type), ContentType.TEXT_PLAIN.withCharset("UTF-8"));//文件类型
        System.out.println("type:"+type);
        builder.addTextBody("fileName", fileName, ContentType.TEXT_PLAIN.withCharset("UTF-8"));//文件名
        System.out.println("fileName:"+fileName);
        builder.addBinaryBody("file", uploadFile);//文件


        HttpEntity entity = builder.build();

        post.setEntity(entity);

        HttpResponse response = httpClient.execute(post);


        if(response.getStatusLine().getStatusCode() == Constants.RESULT_CODE)
        {
            System.out.println("HttpUrlUpload(uploadFile)文件上传成功！！！");
            return true;
        }
        System.out.println("HttpUrlUpload(uploadFile)文件上传失败！！！");
        return false;
    }

    public void uploadFileToServer()
    {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    if(uploadFile())
                    {
                        handler.sendEmptyMessage(Constants.UPLOAD_SUCCESS);
                    }
                    else {
                        handler.sendEmptyMessage(Constants.UPLOAD_FAIL);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();
    }
}
